package api

// 专门对接第三方登录
import (
	restfulspec "github.com/emicklei/go-restful-openapi"
	"github.com/emicklei/go-restful/v3"
	"github.com/infraboard/mcube/app"
	"github.com/infraboard/mcube/http/response"
	"github.com/infraboard/mcube/logger"
	"github.com/infraboard/mcube/logger/zap"

	"gitee.com/go-course/go8/projects/devcloud/mcenter/apps/domain"
	"gitee.com/go-course/go8/projects/devcloud/mcenter/apps/token"
)

var (
	oh = &oauthHandler{}
)

type oauthHandler struct {
	service token.Service
	log     logger.Logger
}

func (h *oauthHandler) Config() error {
	h.log = zap.L().Named(token.AppName)
	h.service = app.GetGrpcApp(token.AppName).(token.Service)
	return nil
}

func (h *oauthHandler) Name() string {
	return "oauth2"
}

func (h *oauthHandler) Version() string {
	return "v1"
}

func (h *oauthHandler) Registry(ws *restful.WebService) {
	tags := []string{"第三方登录"}

	ws.Route(ws.GET("/dingding").To(h.DingDingOauth2Auth).
		Doc("钉钉登陆").
		Metadata(restfulspec.KeyOpenAPITags, tags).
		Param(ws.QueryParameter("authCode", "oauth2 auth code").DataType("string").Required(true)).
		Param(ws.QueryParameter("state", "oauth2 state").DataType("string").Required(false)).
		Param(ws.QueryParameter("domain", "auth domain").DataType("string").DefaultValue(domain.DEFAULT_DOMAIN)).
		Writes(token.Token{}).
		Returns(200, "OK", token.Token{}))
}
func (u *oauthHandler) DingDingOauth2Auth(r *restful.Request, w *restful.Response) {
	req := token.NewDingDingAuthCodeIssueTokenRequest(
		r.QueryParameter("authCode"),
		r.QueryParameter("state"),
	)

	// 颁发Token
	// 需要提前加载APPID和AppSecret相关环境变量: dingding issuer 是通过环境变量获取这些配置的
	tk, err := h.service.IssueToken(r.Request.Context(), req)
	if err != nil {
		response.Failed(w, err)
		return
	}
	tk.SetCookie(w)

	response.Success(w, tk)
}

func init() {
	app.RegistryRESTfulApp(oh)
}
